import React from 'react';
import 'moment-timezone';
import PropTypes from 'prop-types';

import { injectIntl, FormattedMessage } from 'react-intl';
import { stripesConnect } from '@folio/stripes/core';
import { StripesConnectedSource } from '@folio/stripes/smart-components';
import get from 'lodash/get';
import AddActivityForm from './cafe-hub';

class ActivityFormSachet extends React.Component {
  // 声明请求方法
  static manifest = Object.freeze({
    resultCount: { initialValue: 10 },
    activityMessageHttpCommitInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/info'
    },
    activityClassificationHttpInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/property'
    },
    getActivityMessageInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'activity/get_activity_message',
      params: {
        id: ''
      }
    },
    activityResourceHttpInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/auxiliary'
    },
    imageUploadHttpInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/image'
    },
    loadPropertyRecords:{
      type: 'okapi',
      path: 'party/property',
      recordsRequired: '%{resultCount}',

      limitParam: 'limit',
      records: 'propertyGroup',
      GET: {
        params: {
          query: '( isDel = 0 and parentId <> 0 )'
        }
      }
    },
    loadAuxiliaryRecords:{
      type: 'okapi',
      path: 'party/auxiliary',
      recordsRequired: '%{resultCount}',
      limitParam: 'limit',
      other:'totalRecords',
      records: 'auxiliaryGroup',
      GET: {
        params: {
          query: '( isDel = 0 )'
        }
      }
    }
  });

  static propTypes = {
    mutator: PropTypes.shape({
      activityMessageHttpCommitInvoke: PropTypes.shape({
        POST: PropTypes.func.isRequired,
        PUT: PropTypes.func.isRequired
      }),
      getActivityMessageInvoke: PropTypes.shape({
        GET: PropTypes.func.isRequired
      }),
      activityResourceHttpInvoke: PropTypes.shape({
        GET: PropTypes.func.isRequired
      }),

      activityClassificationHttpInvoke: PropTypes.shape({
        GET: PropTypes.func.isRequired
      }),
      imageUploadHttpInvoke: {
        POST: PropTypes.func.isRequired,
        PUT: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired
      },
      loadPropertyRecords:PropTypes.shape({
        PUT: PropTypes.func.isRequired,
        POST: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired,
        DELETE: PropTypes.func.isRequired
      }),
      loadAuxiliaryRecords:PropTypes.shape({
        PUT: PropTypes.func.isRequired,
        POST: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired,
        DELETE: PropTypes.func.isRequired
      })
    }).isRequired,

    stripes: PropTypes.object,
    history: PropTypes.object,
    resources: PropTypes.object,
    name:  PropTypes.string,
  };

  constructor(props) {
    super(props);
    this.logger = props.stripes.logger;
    this.log = this.logger.log.bind(this.logger);
    this.state = {
      activityVenueList: [],
      activityFacilitiesList: [],
      resourceList: [],
      ascriptionList: [],
      creators: [],
      id: '',
      initData: {},
      exitFlag: true,
      operator: {}
    };
    this.source = new StripesConnectedSource(this.props, this.logger, 'loadPropertyRecords');
    this.source = new StripesConnectedSource(this.props, this.logger, 'loadAuxiliaryRecords');
  }

  componentDidMount() {
    // this.getResourceList();
    // this.getClassificationList();

    const { currentUser } = this.props.okapi;
    if (currentUser) {
      const creator = {
        name: `${currentUser.firstName} ${currentUser.lastName}`,
        mobilePhone: currentUser.mobilePhone,
        email: currentUser.email,
        barcode: ''
      };
      const creators = [creator];
      this.setState({
        creators,
        operator: currentUser
      });
    }

    if (!!this.props.params && !!this.props.params.id) {
      const params = this.props.params;
      if (params.id) {
        const id = params.id;
        this.setState({ id });
        this.initData(id);
      }
    }
  }

  getResourceList = (list) => {
    const {   intl } = this.props;
    const activityVenueList = [
      {
        id: '',
        value: '',
        label:intl.formatMessage({id:"ui-party.other.please.select.the.venue.for.the.event"}),
        num: '',
        remainder: ''
      }
    ];
    const activityFacilitiesList = [
      {
        id: '',
        value: '',
        label:  intl.formatMessage({id:'ui-party.other.please.select.the.equipment.required.for.the.event'}),
        num: '',
        remainder: ''
      }
    ];

    if (list) {
      list.forEach(val => {
        const labelName = `${val.name}（${intl.formatMessage({id:'ui-party.other.quantity.available'})}：${val.remainder}）`;
        const tmp = {
          id: val.id,
          value: val.name,
          label: labelName,
          num: val.amount,
          remainder: val.remainder,
          picturesId: val.picturesId
        };

        if (val.typeName === 1) {
          activityVenueList.push(tmp);
        } else if (val.typeName === 2) {
          activityFacilitiesList.push(tmp);
        }
      });

      return {
        activityVenueList,
        activityFacilitiesList,
      };
    }
  };

  getClassificationList = (list) => {
    const {   intl } = this.props;
    if (list) {
      const ascriptionList = [
        {
          value: '',
          label: intl.formatMessage({id:"ui-party.other.please.select.activity.type"})  ,
          id: ''
        }
      ];

      list.forEach(value => {
        const tmp = {
          value: value.name,
          label: value.name,
          id: value.id
        };

        ascriptionList.push(tmp);
      });
      return ascriptionList;
    }
    return [];
  };

  commit = ({ requestPreferences, creds, ...formData }) => {
    const { POST, PUT } = this.props.mutator.activityMessageHttpCommitInvoke;
    const { resources } = this.props;
    const resourceList = this.state.resourceList;
    const {   intl } = this.props;
    const _this = this;
    const loadAuxiliaryRecords = get(resources, 'loadAuxiliaryRecords.records', []);
    const ascriptionList = get(resources, 'loadPropertyRecords.records', []);
    const { activityVenueList, activityFacilitiesList } = this.getResourceList(loadAuxiliaryRecords);

    if (formData.venue) {
      const venueGroup = activityVenueList.filter(item => item.value === formData.venue) || [];
      if (venueGroup.length > 0) {
        const item = venueGroup[0];
        formData.venueId = item.id;
        formData.venuePicturesId = item.picturesId;
      }
    }
    if (formData.facName) {
      const facGroup = activityFacilitiesList.filter(item => item.value === formData.facName) || [];
      if (facGroup.length > 0) {
        const item = facGroup[0];
        formData.facId = item.id;
      }
    }
    if (formData.propertyName) {
      const propertyGroup = ascriptionList.filter(item => item.name === formData.propertyName) || [];
      if (propertyGroup.length > 0) {
        const item = propertyGroup[0];
        formData.propertyId = item.id;
      }
    }

    if (!!formData && !formData.imageId) {
      alert(intl.formatMessage({id:'ui-party.other.please.click.to.upload.event.pictures'}));
      return false;
    }

    if (
      formData.reserveStartDate &&
      formData.reserveStartTime &&
      formData.reserveEndDate &&
      formData.reserveEndTime
    ) {
      formData.reserveStartDate = `${formData.reserveStartDate} ${formData.reserveStartTime}:00`;
      formData.reserveEndDate = `${formData.reserveEndDate} ${formData.reserveEndTime}:59`;
      delete formData.reserveStartTime;
      delete formData.reserveEndTime;
    }
    if (
      formData.attendStartDate &&
      formData.attendStartTime &&
      formData.attendEndDate &&
      formData.attendEndTime
    ) {
      formData.attendStartDate = `${formData.attendStartDate} ${formData.attendStartTime}:00`;
      formData.attendEndDate = `${formData.attendEndDate} ${formData.attendEndTime}:59`;
      delete formData.attendStartTime;
      delete formData.attendEndTime;
    }
    if (
      formData.partyStartDate &&
      formData.partyStartTime &&
      formData.partyEndDate &&
      formData.partyEndTime
    ) {
      formData.partyStartDate = `${formData.partyStartDate} ${formData.partyStartTime}:00`;
      formData.partyEndDate = `${formData.partyEndDate} ${formData.partyEndTime}:59`;
      delete formData.partyStartTime;
      delete formData.partyEndTime;
    }
    if (!formData.remark){
      formData.remark = '该活动未审核'
    }
    formData.isDel = 0;
    formData.approval = 0;
    formData.operator = this.state.operator;
    formData.readerReserveGroup = this.state.creators;
    delete formData.operator.addresses;
    delete formData.operator.preferredContactTypeId;
    delete formData.operator.servicePoints;
    delete formData.operator.curServicePoint;
    delete formData.operator.dateOfBirth;
    if (this.state.id === '') {
      formData.venueCount = 1;
      formData.status = 1;

      POST(formData)
        .then(res => {
          commitResponseInfo(true, '保存成功 ! ');
        })
        .catch(e => {
          console.log(e);
          commitResponseInfo(false, '保存失败 ! ');
        });
    } else {
      PUT(formData)
        .then(res => {
          commitResponseInfo(true, '保存成功 ! ');
        })
        .catch(e => {
          console.log(e);
          commitResponseInfo(false, '保存失败 ! ');
        });
    }

    /**
     * type is commit status
     * @param type type is commit status
     * @param message
     */
    function commitResponseInfo(type, message) {
      if (type) {
        alert(message);
        _this.cancel(false);
      } else {
        alert(message);
      }
    }
  };

  initData = param => {
    const { GET } = this.props.mutator.activityMessageHttpCommitInvoke;
    GET({ path: `party/info/${param}` })
      .then(res => {
        try {
          if (res.reserveStartDate && res.reserveEndDate) {
            const groupByStart = res.reserveStartDate.split(' ');
            const groupByEnd = res.reserveEndDate.split(' ');
            res.reserveStartDate = groupByStart[0];
            res.reserveEndDate = groupByEnd[0];
            res.reserveStartTime = groupByStart[1].substr(0, 5);
            res.reserveEndTime = groupByEnd[1].substr(0, 5);
          }
          if (res.partyStartDate && res.partyEndDate) {
            const groupByStart = res.partyStartDate.split(' ');
            const groupByEnd = res.partyEndDate.split(' ');
            res.partyStartDate = groupByStart[0];
            res.partyEndDate = groupByEnd[0];
            res.partyStartTime = groupByStart[1].substr(0, 5);
            res.partyEndTime = groupByEnd[1].substr(0, 5);
          }
          if (res.attendStartDate && res.attendEndDate) {
            const groupByStart = res.attendStartDate.split(' ');
            const groupByEnd = res.attendEndDate.split(' ');
            res.attendStartDate = groupByStart[0];
            res.attendEndDate = groupByEnd[0];
            res.attendStartTime = groupByStart[1].substr(0, 5);
            res.attendEndTime = groupByEnd[1].substr(0, 5);
          }
        } catch (e) {
          console.debug(e);
        }

        this.setState({
          initData: res
        });
      })
      .catch(e => e);
  };

  cancel = (flag = true) => {
    const { removeTopMenu, matchPath } = this.props;
    removeTopMenu(matchPath, flag);
  };

  render() {

    const { resources } = this.props;
    let venueOrFacilities = {
      activityVenueList:[],
      activityFacilitiesList:[]
    };
    let ascriptionList = [];
    if (this.source) {
      const dataList = get(resources, 'loadPropertyRecords.records', []);
      const loadAuxiliaryRecords = get(resources, 'loadAuxiliaryRecords.records', []);

      venueOrFacilities = this.getResourceList(loadAuxiliaryRecords);
      ascriptionList = this.getClassificationList(dataList);
    }
    return (
      <AddActivityForm
        onSubmit={this.commit}
        stripes={this.props.stripes}
        history={this.props.history}
        venueList={venueOrFacilities.activityVenueList}
        facilitiesList={venueOrFacilities.activityFacilitiesList}
        ascriptionList={ascriptionList}
        initialValues={this.state.initData}
        exitFlag={this.state.exitFlag}
        cancelAction={this.cancel}
        form={this.props.name}
        imageUploadHttpInvoke={this.props.mutator.imageUploadHttpInvoke}
      />
    );
  }
}

export default injectIntl(stripesConnect(ActivityFormSachet));
